<template>
	<view class="page">

		<view class="credentials-container">
			<view class="credentials">
				<image :src="cardBackground[0]" class="bg"></image>
				<view class="cover">
					<image src="../static/filling/card.png" mode="widthFix" class="card"></image>
					<text class="desc">身份证人像面</text>
					<!-- #ifdef MP -->
					<ocr-navigator @onSuccess="scanIdcardFront" certificateType="idCard" :opposite="false">
						<button class="camera"></button>
					</ocr-navigator>
					<!-- #endif -->
				</view>
			</view>
			<view class="credentials">
				<image :src="cardBackground[1]" class="bg"></image>
				<view class="cover">
					<image src="../static/filling/card.png" mode="widthFix" class="card"></image>
					<text class="desc">身份证国徽面</text>
					<!-- #ifdef MP -->
					<ocr-navigator @onSuccess="scanIdcardBack" certificateType="idCard" :opposite="true">
						<button class="camera"></button>
					</ocr-navigator>
					<!-- #endif -->
				</view>
			</view>
			<view class="credentials">
				<image :src="cardBackground[3]" class="bg"></image>
				<view class="cover">
					<image src="../static/filling/card.png" mode="widthFix" class="card"></image>
					<text class="desc">银行卡正面</text>
					<!-- #ifdef MP -->
					<ocr-navigator @onSuccess="scanDrcardFront" certificateType="bankCard">
						<button class="camera"></button>
					</ocr-navigator>
					<!-- #endif -->
				</view>
			</view>
			<view class="credentials">
			    <image :src="cardBackground[2]" class="bg"></image>
			    <view class="cover">
			        <image src="../static/filling/card.png" mode="widthFix" class="card"></image>
			        <text class="desc">手持身份证</text>
			        <button class="camera" @tap="takePhoto('idcardHolding')"></button>
			    </view>
			</view>
			
		</view>
		<view class="title">个人信息</view>
		<view class="list">
			<u-cell-group border="false">
				<u-cell-item title="真实姓名" :value="idcard.username" :value-style="style" :arrow="true" @click="enterContent('姓名','idcard', 'username')" />
				<u-cell-item title="性别" :value="idcard.sex" :value-style="style" :arrow="true" @click="enterContent('性别','idcard', 'sex')" />
				<u-cell-item title="生日" :value="idcard.birthday" :value-style="style" :arrow="true"@click="handleCalendar('idcard', 'birthday')" />
				<u-cell-item title="年龄" :value="idcard.age" :value-style="style" :arrow="true" @click="enterContent('年龄','idcard', 'age')" />
				<u-cell-item title="身份证号" :value="idcard.idcard" :value-style="style" :arrow="true" @click="enterContent('身份证号','idcard', 'idcard')" />
				<u-cell-item title="身份证地址" 
							:value="idcard.address" 
							:value-style="style" :arrow="true" @click="enterContent('身份证地址','idcard', 'address')" />
				<u-cell-item title="身份证有效期" :value="idcard.expiration" :value-style="style" :arrow="true"  @click="handleCalendar('idcard', 'expiration')" />
			</u-cell-group>
		</view>
		<view class="title">用户基本信息</view>
		<view class="list">
			<u-cell-group border="false">
				<u-cell-item title="手机号码" :value="contact.telephone" :value-style="style" @click="enterContent('手机号码','contact', 'telephone')" />
				<u-cell-item title="电子信箱" :value="contact.email" :value-style="style" @click="enterContent('电子信箱','contact', 'email')" />
			</u-cell-group>
		</view>
		<view class="title">银行卡</view>
		<view class="list">
			<u-cell-group border="false">
				<u-cell-item title="银行卡号" :value="drcard.bankcode" :value-style="style" :arrow="true" @click="enterContent('银行卡号','drcard', 'bankcode')" />
				<u-cell-item title="银行卡收款人" :value="drcard.bankusername" :value-style="style" :arrow="true" @click="enterContent('银行卡收款人','drcard', 'bankusername')" />
				<u-cell-item title="银行卡开户行" :value="drcard.bankaddr" :value-style="style" :arrow="true" @click="enterContent('银行卡开户行','drcard', 'bankaddr')" />
			</u-cell-group>
		</view>

		<button class="btn" @tap="save" :disabled="realAuth == 3">保存信息</button>
		<view class="remark">您每次提交实名信息之后，都需要工作人员严格审查，请等候1~3天，这期间您将无法接单，特此声明！</view>
		<u-toast ref="uToast" />
		
		<u-datetime-picker 
		 ref="datetimePicker"
		 v-model="currentTimes"
		 :minDate="new Date('2000-01-01').getTime()"
		 mode="date"
		 :show="showcalendar"
		 @close="showcalendar=false"
		 @confirm="handleSelectDate"></u-datetime-picker>
	</view>
</template>

<script>
let dayjs = require('dayjs');
export default {
	data() {
		return {
			mode: '',
			field: '',
			showcalendar: false,
			currentTimes: new Date().getTime(),
			imgBox: [],
			style: {
				color: '#FF9900'
			},
			currentUser: {},
			// 身份证信息
			idcard: {
				username: "",
				sex: "",
				age: "",
				birthday: "",
				idcard: "",
				address: "",
				expiration: ""
			},
			// 个人信息
			contact: {
				telephone: "",
				email: ""
			},
			// 银行卡信息
			drcard: {
				bankcode: "",
				bankaddr: "",
				bankusername: ""
			},
			// 上传的照片
			uploadImgs: {
				idcardimg1: "",
				idcardimg2: "",
				idcardimg3: "",
				bankimg: ""
			},
			// 四个默认背景图
			cardBackground: [
				'../static/filling/credentials-bg.jpg',
				'../static/filling/credentials-bg.jpg',
				'../static/filling/credentials-bg.jpg',
				'../static/filling/credentials-bg.jpg',
			],
		};
	},
	
	methods: {
		// 身份证人像面数据返回
		scanIdcardFront(resp){
			console.log("身份证人像面的信息是：",resp)
			let that = this
			// 赋值回显
			let detail = resp.detail
			that.idcard.idcard = detail.id.text
			that.idcard.username = detail.name.text
			that.idcard.sex = detail.gender.text
			that.idcard.age = that.getTime2Time(detail.birth.text)
			that.idcard.address = detail.address.text
			that.idcard.birthday = detail.birth.text
			// 同步银行开户人
			that.idcard.bankusername = detail.name.text
			// OCR插件拍摄到的身份证正面照片存储地址
			that.cardBackground[0] = detail.image_path
			// 让身份证View标签加载身份证正面照片
			that.uploadImgs.idcardimg1 = detail.image_path
			console.log("图片开始上传")
			// 把拍摄的身份证照片上传的云服务器
			that.$request.upload(that.$api.uploadCosPrivateFile,detail.image_path, {"module":'xxb/auth'}).then(resData=>{
				console.log("图片上传成功")
				// 上传文件的相对路径
				// 因为可能上传的过程中，用户拍摄了几次身份证的正反面或者是银行卡照片，所以就可能存储很多垃圾图片在云服务器上
				let path = resData.path
				// 把上传成功的完整路径，要入库的字段也更改成真实的图片路径
				that.uploadImgs.idcardimg1 = resData.url
				// 预览成真实的身份证路径
				that.cardBackground[0] = resData.url
				// 把相对路径存储到数组中，用来做垃圾
				that.imgBox.push(path)
				// 上传完图片之后直接保存
				this.save()
			});
		},
		// 身份证国徽面数据返回
		scanIdcardBack(){
			console.log("身份证国徽面的信息是：",resp)
			let that = this
			let detail = resp.detail
			// View标签加载身份证背面照片
			that.cardBackground[1] = detail.image_path
			// OCR插件拍摄到的身份证背面照片存储地址
			that.uploadImgs.idcardimg2 = detail.image_path
			// 过期时间格式化
			let validDate = detail.valid_date.text.split('-')[1]
			// 格式化截至日期
			that.idcard.expiration = dayjs(validDate, 'YYYYMMDD').format('YYYY-MM-DD')
			// 把拍摄的身份证照片上传的云服务器
			that.$request.updload(that.$api.uploadCosPrivateFile, detail.image_path, {"module":'xxb/auth'}).then(resData=>{
				let path = resData.path
				that.uploadImgs.idcardimg2 = resData.url
				that.cardBackground[1] = resData.url
				that.imgBox.push(path)
			})
			// 上传完图片之后直接保存
			this.save()
		},
		// 银行卡正面数据返回
		scanDrcardFront(){
			console.log("银行卡的信息是：",resp)
			console.log("身份证反面的信息是：",resp)
			let that = this
			let detail = resp.detail
			// View标签加载身份证背面照片
			that.cardBackground[2] = detail.image_path
			// OCR插件拍摄到的身份证背面照片存储地址
			that.uploadImgs.bankimg = detail.image_path
			// 银行卡号
			that.drcard.bankcode = detail.number.text
			that.$request.upload(that.$api.uploadCosFile, detail.image_path, {"module":'xxb/bank'}).then(resData=>{
				let path = resData.path
				that.uploadImgs.bankimg = resData.url
				that.cardBackground[2]=resData.url
				that.imgBox.push(path)
			})
			// 上传完图片之后直接保存
			this.save()
		},
		// 手持身份证页面跳转
		takePhoto(){
			let that = this
			// 如果是小程序就执行下面逻辑
			// #ifdef MP-WEIXIN
			uni.navigateTo({
				url: "/identity/identity_camera/identity_camera"
			})	
			// #endif 

			// 如果是APP就执行此处
			// #ifdef APP
			uni.chooseImage({
				// 默认9
				count: 1,
				// 可以指定是原图还是压缩图，默认二者都有
				sizeType: ['original', 'compressed'],
				success: function (res) {
					// 文件上传
					console.log(JSON.stringify(res.tempFilePaths[0]))
					that.updatePhoto(res.tempFilePaths[0])
				},
				fail(err){
					this.$toast("图片获取失败...")
				}
			})
			// #endif 
		},
		updatePhoto(photoPath){
			let that = this
			console.log("photoPath",photoPath)
			// 预览成真实的身份证路径
			that.cardBackground[3] = photoPath
			// 把上传成功的完整路径，要入库的字段也更改成真实的图片路径
			that.uploadImgs.idcardimg3 = photoPath
			
			// 把手持的照片上传到云服务器
			that.$request.upload(that.$api.uploadCosPrivateFile, photoPath, {"module":'xxb/handphoto'}).then(resData=>{
				let path = resData.path
				that.uploadImgs.idcardimg3 = resData.url
				that.cardBackground[3]=resData.url
				that.imgBox.push(path)
			})
			// 上传完图片之后直接保存
			this.save()

		},
		// 修改弹窗数据
		enterContent: function(title,mode,key) {
			let that = this;
			uni.showModal({
				title: title,
				editable: true,
				content: that[mode][key],
				success(resp) {
					if(resp.confirm) {
						// resp.content是我输入的值
						if(resp.content){
							console.log("resp.content",resp.content)
							that[mode][key] = resp.content
						}
					}
				}
			});
		},
		// 初始化日期
		formatter(type, value) {
			var arr = [];
			if (type === 'year') {
				return `${value}`
			}
			if (type === 'month') {
				return `${value}月`
			}
			if (type === 'day') {
				return `${value}日`
			}
			
		},
		// 获取日期和当前时间相减得到年龄
		getTime2Time($time1){
			var time1 = new Date()/1000;
			var time2 = Date.parse($time1)/1000;
			var time_ = time1 - time2;
			return Math.floor((time_/(3600*24))/365);
		},
		// 打开日历窗口
		handleCalendar(mode,key){
			console.log(mode,key)
			this.showcalendar = true
			this.mode = mode
			this.field = key
			
			// 目的：是把之前的值渲染到组件上
			let timer = this[this.mode][this.field]
			console.log("上一个我遗留的数据，不知道是什么timer",timer)
			// 回填我选中的数据
			this.currentTimes = new Date(timer).getTime()
			console.log("currentTimes",currentTimes)
		},
		// 选中的数据，进行赋值(data 是选中的值)
		handleSelectDate(date){
			// mode -idcard   field -birthday
			this[this.mode][this.field] = dayjs(date.value).format("YYYY-MM-DD")
			console.log("this[this.mode][this.field]",this[this.mode][this.field])
			// 选中之后关闭窗口
			this.showcalendar = false
		},
		async save(){
			// 参数传递，对象合并（解构）
			const params = {
				...this.idcard,
				...this.contact,
				...this.drcard,
				...this.uploadImgs
			}
			params.sex = params.sex == "男" ? 1 : 0;
			const resData = await this.$request.post(this.$api.updateUserInfo,params)
			console.log("resData",resData)
			// 提示
			this.$toast("更改用户信息成功")
			console.log("1111111111111111111111111111111111111111")
			// 跳转到人脸识别
			setTimeout(()=>{
				uni.reLaunch({
					url: "/identity/face_camera/face_camera"
				})
			},1000)
		},
		
		
		
	},
	onReady() {
		// 微信小程序需要用此写法
		this.$refs.datetimePicker.setFormatter(this.formatter)
	},
	
	onShow(){
		// 判断用户登录的状态
		const isLogin = this.$cache.get("isLogin")
		if(isLogin){
			// 如果登录就获取登录的用户信息
			// 登录的信息是放到缓存当中的，这个时候如果上传了信息，缓存是没有的，数据库却已经更新了，如果想要同步
			// 			1.更新的时候修改数据库，也要同步前端缓存
			// 			2.直接查询数据库，保存与数据库最新
			this.currentUser = this.$cache.get("user")
			// 执行数据库查询，实时同步数据库的信息
			this.$getUserInfo().then(resData=>{
				this.currentUser = resData.user
				this.$cache.set("user",resData.user)
				
				
				// 身份证信息
				const {username,sex,age,birthday,idcard,address,expiration} = this.currentUser
				// 个人信息
				const {email,telephone} = this.currentUser
				// 银行卡信息
				const {bankcode,bankaddr,bankusername} = this.currentUser
				// 上传的照片
				const {idcardimg1,idcardimg2,idcardimg3,bankimg} = this.currentUser
				// 赋值
				this.idcard = {username,sex:sex==1?'男':'女',age,birthday,idcard,address,expiration}
				this.contact = {email,telephone}
				this.drcard = {bankcode,bankaddr,bankusername}
				this.uploadImgs = {idcardimg1,idcardimg2,idcardimg3,bankimg}
				// 如果图片没有。那么就不赋值
				if(idcardimg1){
					this.cardBackground[0]=idcardimg1
				}
				if(idcardimg2){
					this.cardBackground[1]=idcardimg2
				}
				if(idcardimg3){
					this.cardBackground[2]=idcardimg3
				}
				if(bankimg){
					this.cardBackground[3]=bankimg
				}
			})
		}else{
			// 3: 如果没有登录就去登录
			uni.redirectTo({
				url:"/login/login"
			})
		}
	}
};
</script>

<style lang="less">
@import url('filling.less');
</style>
